ID3 Calssifier¶
ID3 stands for Iterative Dichotomiser 3.
- Target feature:
play - We split the dataset based on the feature that has the maximum information gain.
- We keep repeating this process until the whole dataset is classified on the basis of the key feature.
Theory¶
Entropy of a dataset¶
$$\text{Entropy}(T, key) = -\sum_{i=0}^n p_i\log_2(p_i)$$
- $T$ represents the dataset.
- $key$ represents the column for which we find the entropy.
- $p_i$ is the probability of being selected, of each of the unique values of the key feature. In our case, the key feature is
play.
Information Gain of a feature¶
$$\text{Information Gain = Entropy(dataset, target feature)}-\sum_{i=0}^n \text{Probability of}\ f_i\times\text{Entropy}( \sigma_{f=f_i}\text{dataset}, \text{target feature})$$
- $f_i$ is the $i$-th unique value of that feature.
- $\text{Entropy of}\ f_i$ is the entropy of the dataset, that has $f_i$ as that value for feature $f$, w.r.t. the key feature.
Note: Decision Trees classifiers are prone to over-fitting.
Refer to the video below for more information¶
from IPython.display import YouTubeVideo as YTV
videos = ['CWzpomtLqqs']
for video in videos:
v = YTV(video, height = 370, width = 600)
display(v)
Importing the dataset¶
import numpy as np
import pandas as pd
data = pd.read_csv("./PlayTennis.csv")
data
| weather | temp | humidity | windy | play | |
|---|---|---|---|---|---|
| 0 | sunny | hot | high | False | no |
| 1 | sunny | hot | high | True | no |
| 2 | overcast | hot | high | False | yes |
| 3 | rainy | mild | high | False | yes |
| 4 | rainy | cool | normal | False | yes |
| 5 | rainy | cool | normal | True | no |
| 6 | overcast | cool | normal | True | yes |
| 7 | sunny | mild | high | False | no |
| 8 | sunny | cool | normal | False | yes |
| 9 | rainy | mild | normal | False | yes |
| 10 | sunny | mild | normal | True | yes |
| 11 | overcast | mild | high | True | yes |
| 12 | overcast | hot | normal | False | yes |
| 13 | rainy | mild | high | True | no |
Entropy of the whole dataset¶
from math import log
log2 = log(2)
def calc_entropy(dataset, key = "play"):
categories = dataset[key].unique()
total_no_obs = dataset.shape[0]
entropy_dataset = 0.0
for category in categories:
number = dataset[dataset[key] == category].shape[0]
prob = float(number) / float(total_no_obs)
entropy_dataset -= (prob * log(prob))
return entropy_dataset / log2
entropy_full = calc_entropy(data, "play")
entropy_full
0.940285958670631
Determining the Root Node¶
import json
def get_root_node(dataset, key = "play"):
inf_gain_map = {}
for col in dataset.columns:
if col != key:
features_array = dataset[col].unique()
inf_gain = calc_entropy(dataset)
for category in features_array:
tmp_dataset = dataset[dataset[col] == category]
entropy = calc_entropy(tmp_dataset)
prob = float(tmp_dataset.shape[0]) / float(dataset.shape[0])
inf_gain -= (entropy * prob)
inf_gain_map[col] = inf_gain
root_feature = max(zip(inf_gain_map.values(), inf_gain_map.keys()))[1]
return root_feature, inf_gain_map
root1, if_gain_map = get_root_node(data)
print(f"First split feature: {root1}")
print(json.dumps(if_gain_map, indent = 4))
First split feature: weather
{
"weather": 0.246749819774439,
"temp": 0.029222565658954758,
"humidity": 0.15183550136234159,
"windy": 0.04812703040826943
}
As we can see, the weather feature has the maximum Information gain. So that will be the root node and we will first split our dataset on the basis of weather.
features_array = data.weather.unique()
split_datasets_1 = []
for category in features_array:
split_datasets_1.append(data[data.weather == category])
split_datasets_1[0]
| weather | temp | humidity | windy | play | |
|---|---|---|---|---|---|
| 0 | sunny | hot | high | False | no |
| 1 | sunny | hot | high | True | no |
| 7 | sunny | mild | high | False | no |
| 8 | sunny | cool | normal | False | yes |
| 10 | sunny | mild | normal | True | yes |
split_datasets_1[1]
| weather | temp | humidity | windy | play | |
|---|---|---|---|---|---|
| 2 | overcast | hot | high | False | yes |
| 6 | overcast | cool | normal | True | yes |
| 11 | overcast | mild | high | True | yes |
| 12 | overcast | hot | normal | False | yes |
split_datasets_1[2]
| weather | temp | humidity | windy | play | |
|---|---|---|---|---|---|
| 3 | rainy | mild | high | False | yes |
| 4 | rainy | cool | normal | False | yes |
| 5 | rainy | cool | normal | True | no |
| 9 | rainy | mild | normal | False | yes |
| 13 | rainy | mild | high | True | no |
As we can see, when the weather is overcast then the player will always play regardless of the other features. Now we need to find the feature which has the maximum information gain in the first dataset split where weather is sunny.
Determining the second root node¶
base_data_set = split_datasets_1[0]
root2, if_gain_map = get_root_node(base_data_set)
print(f"Second split feature: {root2}")
print(json.dumps(if_gain_map, indent = 4))
Second split feature: humidity
{
"weather": 0.0,
"temp": 0.5709505944546688,
"humidity": 0.9709505944546688,
"windy": 0.019973094021975113
}
As we can see, the humdity feature has the maximum Information gain. So that will be the root node and we will first split our dataset on the basis of humdity.
Note: Since all values of weather are same, it's entropy is 0.
features_array = data.humidity.unique()
split_datasets_2 = []
for category in features_array:
split_datasets_2.append(base_data_set[base_data_set.humidity == category])
split_datasets_2[0]
| weather | temp | humidity | windy | play | |
|---|---|---|---|---|---|
| 0 | sunny | hot | high | False | no |
| 1 | sunny | hot | high | True | no |
| 7 | sunny | mild | high | False | no |
split_datasets_2[1]
| weather | temp | humidity | windy | play | |
|---|---|---|---|---|---|
| 8 | sunny | cool | normal | False | yes |
| 10 | sunny | mild | normal | True | yes |
Now we need to do the same with the third split dataset.
Determining the third root node¶
base_data_set = split_datasets_1[2]
root3, if_gain_map = get_root_node(base_data_set)
print(f"Third split feature: {root3}")
print(json.dumps(if_gain_map, indent = 4))
Third split feature: windy
{
"weather": 0.0,
"temp": 0.019973094021975113,
"humidity": 0.019973094021975113,
"windy": 0.9709505944546688
}
features_array = data.windy.unique()
split_datasets_3 = []
for category in features_array:
split_datasets_3.append(base_data_set[base_data_set.windy == category])
split_datasets_3[0]
| weather | temp | humidity | windy | play | |
|---|---|---|---|---|---|
| 3 | rainy | mild | high | False | yes |
| 4 | rainy | cool | normal | False | yes |
| 9 | rainy | mild | normal | False | yes |
split_datasets_3[1]
| weather | temp | humidity | windy | play | |
|---|---|---|---|---|---|
| 5 | rainy | cool | normal | True | no |
| 13 | rainy | mild | high | True | no |
from sklearn.preprocessing import LabelEncoder
Le = LabelEncoder()
data['weather'] = Le.fit_transform(data['weather'])
data['temp'] = Le.fit_transform(data['temp'])
data['humidity'] = Le.fit_transform(data['humidity'])
data['windy'] = Le.fit_transform(data['windy'])
data['play'] = Le.fit_transform(data['play'])
data
| weather | temp | humidity | windy | play | |
|---|---|---|---|---|---|
| 0 | 2 | 1 | 0 | 0 | 0 |
| 1 | 2 | 1 | 0 | 1 | 0 |
| 2 | 0 | 1 | 0 | 0 | 1 |
| 3 | 1 | 2 | 0 | 0 | 1 |
| 4 | 1 | 0 | 1 | 0 | 1 |
| 5 | 1 | 0 | 1 | 1 | 0 |
| 6 | 0 | 0 | 1 | 1 | 1 |
| 7 | 2 | 2 | 0 | 0 | 0 |
| 8 | 2 | 0 | 1 | 0 | 1 |
| 9 | 1 | 2 | 1 | 0 | 1 |
| 10 | 2 | 2 | 1 | 1 | 1 |
| 11 | 0 | 2 | 0 | 1 | 1 |
| 12 | 0 | 1 | 1 | 0 | 1 |
| 13 | 1 | 2 | 0 | 1 | 0 |
features_cols = ['weather','temp','humidity','windy']
X = data[features_cols]
Y = data.play
Creating the Classifier¶
from sklearn.tree import DecisionTreeClassifier
classifier = DecisionTreeClassifier(criterion = 'entropy')
consume_output = classifier.fit(X, Y)
Testing the Classifier¶
classifier.predict(X)
array([0, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0])
classifier.score(X, Y)
1.0
Visualizing the Decision Tree Classifier¶
from sklearn import tree
clf = tree.DecisionTreeClassifier(criterion = 'entropy')
clf = clf.fit(X, Y)
tree.plot_tree(clf, filled = True)
[Text(0.4, 0.9, 'x[0] <= 0.5\nentropy = 0.94\nsamples = 14\nvalue = [5, 9]'), Text(0.3, 0.7, 'entropy = 0.0\nsamples = 4\nvalue = [0, 4]'), Text(0.5, 0.7, 'x[2] <= 0.5\nentropy = 1.0\nsamples = 10\nvalue = [5, 5]'), Text(0.3, 0.5, 'x[0] <= 1.5\nentropy = 0.722\nsamples = 5\nvalue = [4, 1]'), Text(0.2, 0.3, 'x[3] <= 0.5\nentropy = 1.0\nsamples = 2\nvalue = [1, 1]'), Text(0.1, 0.1, 'entropy = 0.0\nsamples = 1\nvalue = [0, 1]'), Text(0.3, 0.1, 'entropy = 0.0\nsamples = 1\nvalue = [1, 0]'), Text(0.4, 0.3, 'entropy = 0.0\nsamples = 3\nvalue = [3, 0]'), Text(0.7, 0.5, 'x[3] <= 0.5\nentropy = 0.722\nsamples = 5\nvalue = [1, 4]'), Text(0.6, 0.3, 'entropy = 0.0\nsamples = 3\nvalue = [0, 3]'), Text(0.8, 0.3, 'x[1] <= 1.0\nentropy = 1.0\nsamples = 2\nvalue = [1, 1]'), Text(0.7, 0.1, 'entropy = 0.0\nsamples = 1\nvalue = [1, 0]'), Text(0.9, 0.1, 'entropy = 0.0\nsamples = 1\nvalue = [0, 1]')]
import graphviz
dot_data = tree.export_graphviz(clf, out_file=None)
graph = graphviz.Source(dot_data)
graph